﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;

namespace BrnMall.Sdk.WeiXin.Tool
{
    public class Encrypt
    {
        /// <summary>
        /// 平台证书解密
        /// </summary>
        /// <param name="text">密文</param>
        /// <param name="nonce">随机数</param>
        /// <returns></returns>
        public static string DecryptCert(string mchKey, string text, string nonce)
        {
            var postData = "{\"chkey\":\"" + mchKey + "\",\"nonce\": \"" + nonce + "\",\"ciphertext\": \"" + text + "\" }";
            var json = RestHttp.JsonPost("http://wxapp.sz-pbdata.com:8080/pbServer/external/decrypt", postData);
            Regex r = new Regex("\"data\":\"([\\w\\W]+?)\"");
            var key = r.Match(json).Groups[1].Value.Replace("\\n", "");

            //过滤头尾标记(BEGIN和 END)
            var start = "BEGIN CERTIFICATE-----";
            var startIndex = key.IndexOf(start) + start.Length;
            return key.Substring(startIndex, key.LastIndexOf("-----END CERTIFICATE") - startIndex);
        }

        /// <summary>
        /// 敏感信息加密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="publicKeyDER"></param>
        /// <returns></returns>
        public static string EncryptFeild(string text, byte[] publicKeyDER)
        {
            var x509 = new X509Certificate2(publicKeyDER);
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key;
            var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), false);
            return Convert.ToBase64String(buff);
        }

        public static string HmacSHA256(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashmessage.Length; i++)
                {
                    builder.Append(hashmessage[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="encypStr">加密字符串</param>
        /// <param name="charset">编码方式</param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, string charset = "utf-8")
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }
    }
}
